package com.managerProvider.service.impl;

import com.managerProvider.mapper.RoleMapper;
import com.managerProvider.mapper.UrMapper;
import com.managerProvider.mapper.UserMapper;
import com.managerProvider.service.UserService;
import entity.ResponseMessage;
import entity.StatusCode;
import entity.Ur;
import entity.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import util.DeleteFile;
import util.RegexUtil;

import java.util.List;

/**
 * 用户服务impl
 * The type User service.
 *
 * @author tapoliuliyue
 * @date 2022 /04/23
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    /**
     * The Role mapper.
     */
    @Autowired
    private RoleMapper roleMapper;
    /**
     * The Ur mapper.
     */
    @Autowired
    private UrMapper urMapper;
    /**
     * The Encoder.
     */
    @Autowired
    private BCryptPasswordEncoder encoder;

    /**
     * The Logger.
     */
    private Logger logger = Logger.getLogger(this.getClass());

    /**
     * Find all user response message.
     *
     * @param user the user
     * @return the response message
     */
    @Override
    public ResponseMessage findAllUser(User user) {
        ResponseMessage msg = new ResponseMessage();
        try {
            List<User> allUser = userMapper.findAllUser(user);
            if (allUser == null || allUser.size() == 0) {
                msg.setCode(StatusCode.ERROR);
                msg.setMessage("find all user result is empty");
                msg.setFlag(false);
                logger.debug("UserServiceImpl findAllUser params:" + user + ",result:" + allUser);
                return msg;
            }
            msg.setCode(StatusCode.OK);
            msg.setData(allUser);
            msg.setFlag(true);
            msg.setMessage("ok");
            return msg;
        } catch (Exception e) {
            e.printStackTrace();
            msg.setMessage("UserServiceImpl findAllUser error");
            msg.setCode(StatusCode.ERROR);
            msg.setFlag(false);
            logger.error("UserServiceImpl findAllUser params:" + user + ",result:" + e);
            return msg;
        }
    }

    /**
     * Delete by id response message.
     *
     * @param id the id
     * @return the response message
     */
    @Override
    public ResponseMessage deleteById(String id) {
        ResponseMessage msg = new ResponseMessage();
        try {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(StatusCode.ERROR);
                msg.setMessage("参数错误");
                msg.setFlag(false);
                logger.debug("UserServiceImpl deleteById params:" + id);
                return msg;
            }
            int delete = userMapper.deleteById(id);
            if (delete <= 0) {
                msg.setCode(StatusCode.ERROR);
                msg.setMessage("delete user failed");
                msg.setFlag(false);
                logger.debug("UserServiceImpl deleteById params:" + id + ",result:" + delete);
                return msg;
            }
            msg.setCode(StatusCode.OK);
            msg.setData(delete);
            msg.setMessage("ok");
            msg.setFlag(true);
            logger.debug("UserServiceImpl deleteById params:" + id + ",result:" + delete);
            return msg;
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(StatusCode.ERROR);
            msg.setMessage("delete user error");
            msg.setFlag(false);
            logger.error("UserServiceImpl deleteById params:" + id + ",result:" + e);
            return msg;
        }
    }


    /**
     * Insert user response message.
     *
     * @param user the user
     * @return the response message
     */
    @Override
    public ResponseMessage insertUser(User user) {

        ResponseMessage msg = new ResponseMessage();
        //验证前端传来的用户名是否以及存在
        String queryUserName = user.getUserName();
        User selectUser = new User();
        selectUser.setUserName(queryUserName);
        List<User> queryList = userMapper.selectOneUser(selectUser);
        if (queryList != null || queryList.size() > 0) {
            msg.setCode(StatusCode.ERROR);
            msg.setFlag(false);
            msg.setMessage("insert user userName is already exist");
            logger.debug("UserServiceImpl insertUser insert user params:" + user + ",result:userName is already exist");
            return msg;
        }
        try {
            if (user == null || RegexUtil.checkMobile(user.getMobile()) || RegexUtil.checkPassword(user.getPassword()) ||
                    RegexUtil.checkEmail(user.getEmail())) {
                msg.setCode(StatusCode.ERROR);
                msg.setMessage("参数错误");
                msg.setFlag(false);
                logger.debug("UserServiceImpl insertUser params:" + user);
                return msg;
            }
            String password = user.getPassword();
            //将密码进行springSecurity加盐加密
            String encodePassword = encoder.encode(password);
            user.setPassword(encodePassword);
            //新增用户
            int insert = userMapper.insert(user);
            //获取新增用户勾选的角色
            List<String> roleIdList = user.getRoleIdList();
            //获取用户名
            String userName = user.getUserName();
            if (insert <= 0) {
                msg.setCode(StatusCode.ERROR);
                msg.setMessage("insertUser failed");
                msg.setFlag(false);
                logger.debug("UserServiceImpl insertUser params:" + user + ",result:" + insert);
                return msg;
            }
            msg.setCode(StatusCode.OK);
            msg.setData(insert);
            msg.setMessage("ok");
            msg.setFlag(true);
            //构建新的用户对象，用来存入添加ur表数据的参数
            User userSelect = new User();
            //存入用户名
            userSelect.setUserName(userName);
            //根据刚添加的用户名，获取刚新增的用户信息
            ResponseMessage msgQuery = this.selectOneUser(userSelect);
            //查询成功的情况
            if (msgQuery.isFlag() == true) {
                //获取结果对象的data
                List<User> list = (List<User>) msgQuery.getData();
                //获取的是个list，但正常情况只会有一个数据，获取刚新增的用户的id
                String userIdQuery = list.get(0).getId();
                //循环传入的角色集合
                for (int i = 0; i < roleIdList.size(); i++) {
                    //构建新的ur对象，用来接收新增ur表数据
                    Ur ur = new Ur();
                    //ur存入角色id
                    ur.setRoleId(roleIdList.get(i));
                    //ur存入用户id
                    ur.setUserId(userIdQuery);
                    //ur新增
                    int insertUr = urMapper.insert(ur);
                }
            }
            logger.debug("UserServiceImpl insertUser params:" + user + ",result:" + insert);
            return msg;
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(StatusCode.ERROR);
            msg.setMessage("insertUser error");
            msg.setFlag(false);
            logger.error("UserServiceImpl insertUser params:" + user + ",result:" + e);
            return msg;
        }
    }

    /**
     * Update user response message.
     *
     * @param user the user
     * @return the response message
     */
    @Override
    public ResponseMessage updateUser(User user) {

        ResponseMessage msg = new ResponseMessage();
        RegexUtil regexUtil = new RegexUtil();
        boolean deleteImg = true;
        try {
            List<User> selectList = userMapper.selectList(null);
            //获取前端传来的用户id
            String id = user.getId();
            User userQuery = new User();
            userQuery.setId(id);
            //根据id查询出用户原来的信息
            List<User> userList = userMapper.selectOneUser(userQuery);
            if (!userList.get(0).getUserName().equals(user.getUserName())) {
                boolean checkExist = regexUtil.checkExist(user.getUserName(), selectList);
                if (!checkExist) {
                    msg.setCode(StatusCode.ERROR);
                    msg.setMessage("参数错误");
                    msg.setFlag(false);
                    logger.debug("UserServiceImpl updateUser params:" + user);
                    return msg;
                }
            }
            if (user == null || !RegexUtil.checkEmail(user.getEmail()) || !RegexUtil.checkMobile(user.getEmail()) ||
                    !RegexUtil.checkEmail(user.getEmail())
            ) {
                msg.setCode(StatusCode.ERROR);
                msg.setFlag(false);
                msg.setMessage("参数错误");
                logger.debug("UserServiceImpl updateUser params:" + user);
                return msg;
            }

            String newLogo = user.getLogo();

            String logo = userList.get(0).getLogo();

            if (newLogo != null && !"".equals(newLogo) && !newLogo.equals(logo)) {
                //删除原logo
                deleteImg = DeleteFile.delStoreLogo(logo);
            }
            //获取前端传来的密码
            String password = user.getPassword();
            //将密码进行加盐加密
            String encodePassword = encoder.encode(password);
            user.setPassword(encodePassword);
            //修改用户
            int update = userMapper.updateById(user);
            if (update <= 0 || deleteImg == false) {
                msg.setCode(StatusCode.ERROR);
                msg.setMessage("updateUser failed");
                msg.setFlag(false);
                logger.debug("UserServiceImpl updateUser params:" + user + ",result:" + update);
                return msg;
            }
            //修改用户的id
            String userId = user.getId();
            //根据用户id，先删除该用户在ur表的数据
            int deleteUr = urMapper.deleteByUserId(userId);
            //获取修改用户修改的角色id集合
            List<String> roleIdList = user.getRoleIdList();
            //遍历角色id集合
            for (int i = 0; i < roleIdList.size(); i++) {
                //获取第i个角色id
                String roleId = roleIdList.get(i);
                //构建新的ur对象，用来接收新增ur表的数据
                Ur ur = new Ur();
                //ur存入用户id
                ur.setUserId(userId);
                //ur存入角色id
                ur.setRoleId(roleId);
                //ur表插入数据
                urMapper.insert(ur);
            }
            msg.setCode(StatusCode.OK);
            msg.setData(update);
            msg.setMessage("ok");
            msg.setFlag(true);
            logger.debug("UserServiceImpl updateUser params:" + user + ",result:" + update);
            return msg;
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(StatusCode.ERROR);
            msg.setMessage("updateUser error");
            msg.setFlag(false);
            logger.error("UserServiceImpl updateUser params:" + user + ",result:" + e);
            return msg;
        }
    }

    /**
     * Select one user response message.
     *
     * @param user the user
     * @return the response message
     */
    @Override
    public ResponseMessage selectOneUser(User user) {
        ResponseMessage msg = new ResponseMessage();
        try {
            List<User> allUser = userMapper.selectOneUser(user);
            if (allUser == null || allUser.size() == 0) {
                msg.setCode(StatusCode.ERROR);
                msg.setMessage("selectOneUser result is empty");
                msg.setFlag(false);
                logger.debug("UserServiceImpl selectOneUser params:" + user + ",result:" + allUser);
                return msg;
            }
            msg.setCode(StatusCode.OK);
            msg.setData(allUser);
            msg.setFlag(true);
            msg.setMessage("ok");
            return msg;
        } catch (Exception e) {
            e.printStackTrace();
            msg.setMessage("UserServiceImpl selectOneUser error");
            msg.setCode(StatusCode.ERROR);
            msg.setFlag(false);
            logger.error("UserServiceImpl selectOneUser params:" + user + ",result:" + e);
            return msg;
        }
    }

    /**
     * Select one user role power response message.
     *
     * @param user the user
     * @return the response message
     */
    @Override
    public ResponseMessage selectOneUserRolePower(User user) {
        logger.info("UserServiceImpl selectOneUserRolePower params:" + user);
        ResponseMessage msg = new ResponseMessage();
        try {
            List<User> userList = userMapper.selectOneUserRolePower(user);
            if (userList == null || userList.size() == 0) {
                msg.setCode(StatusCode.ERROR);
                msg.setFlag(false);
                msg.setMessage("UserServiceImpl selectOneUserRolePower result is empty");
                logger.debug("UserServiceImpl selectOneUserRolePower params:" + user + ",result:" + userList);
                return msg;
            }
            msg.setCode(StatusCode.OK);
            msg.setFlag(true);
            msg.setMessage("ok");
            msg.setData(userList);
            logger.debug("UserServiceImpl selectOneUserRolePower params:" + user + ",result:" + userList);
            return msg;
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(StatusCode.ERROR);
            msg.setFlag(false);
            msg.setMessage("UserServiceImpl selectOneUserRolePower is error");
            logger.error("UserServiceImpl selectOneUserRolePower params:" + user + ",result:" + e);
            return msg;
        }
    }
}
